package com.kgcx.order.rabbitmq;

import com.kgcx.common.client.schedule.pojo.ScheduleRecord;
import com.kgcx.common.eum.OrderEnum;
import com.kgcx.core.utils.JsonUtil;
import com.kgcx.order.domain.Order;
import com.kgcx.order.entity.OrderChangeMessage;
import com.kgcx.order.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * Created by zhulong on 17/11/13.
 * 运力检查成功
 */
@Component

public class TransportCapacityCheckSuccessListener {

    private static final Logger LOG = LoggerFactory.getLogger(TransportCapacityCheckSuccessListener.class);
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private OrderService service;

    @RabbitListener(queues = "kgcxOrderTransportCapacityCheckSuccessQueue", errorHandler = "custRabbitListenerErrorHandler")
    public void processOrderStatus(String json) {
        LOG.info("订单 - 运力检查结果：充足，json=" + json);

//        ScheduleRecord scheduleRecord = gson.fromJson(json, ScheduleRecord.class);
        ScheduleRecord scheduleRecord = JsonUtil.toObject(json, ScheduleRecord.class);

        //获取订单详情，如果订单为预约单，则改变订单状态为预约成功
        Order order = service.getIngOrderByOrderNo(scheduleRecord.getOrder_no());
        if (order != null) {
            if (!order.getOrderType().equals(OrderEnum.TYPE_IMMEDIATELY_PLANE_PICK)
                    && !order.getOrderType().equals(OrderEnum.TYPE_IMMEDIATELY_TRAIN_PICK)
                    && !order.getOrderType().equals(OrderEnum.TYPE_IMMEDIATELY_COMMON)) {
                stringRedisTemplate.opsForHash()
                        .put(OrderEnum.ORDERS_STATUS, scheduleRecord.getOrder_no(),
                                String.valueOf(OrderEnum.PLAN_SUCCESS));

                //TODO 如果是预约用车 mqtt发给用户端 预约成功
                OrderChangeMessage mqMsg = new OrderChangeMessage(order.getOrderNo()
                        , OrderEnum.PLAN_SUCCESS, OrderChangeMessage.MESSAGE_TYPE_PLAN_SUCCESS, "", order.getPlacingUserId());
                service.sendMqtt(JsonUtil.toString(mqMsg)
                        , OrderEnum.ORDER_STATE_TOPIC + "." + order.getPlacingUserId());
            }
        }


    }
}